import { createApp, nextTick, reactive, ref } from 'vue';
import { UUID } from 'uuidjs';
import { ConfigProvider } from 'ant-design-vue';
import zhCN from 'ant-design-vue/es/locale/zh_CN';
import ModalComponent from '@/components/common/modal-service.vue';
import ModalForm from '@/components/common/form.vue';
import { deepClone } from '@/utils/index';

interface ModalOption {
  title?: string; // 标题
  width?: string;
  height?: string;
  wrapClassName?: string;
  wrapStyle?: any;
  mask?: boolean;
  destroyOnClose?: boolean;
  centered?: boolean;
  showResetBtn?: boolean;
  showConfirmBtn?: boolean;
  confirmBtnText?: string;
  cancelBtnText?: string;
  showCancelBtn?: boolean;
  showFooter?: boolean;
}
export interface Options {
  modalOption: ModalOption;
  onClose?: () => void;
  onOk?: (model?: Model) => void;
  onReset?: () => void;
  formList?: any[];
  formData?: Model;
  component?: any;
}

interface Model {
  [key: string]: any;
}

export type ModalFunc = (options: Options) => {
  handleShow: () => void;
  handleClose: () => void;
  handleLoading: (value: boolean) => void;
  updateModalOptions: (modalOption: ModalOption) => void;
  handleReset: () => void;
};

export default function useModal(options: Options) {
  let globalModalDiv: HTMLDivElement | null = null;
  let globalApp: any = null;
  const show: any = ref(false); // 弹窗是否显示
  const loading: any = ref(false); // 弹窗是否显示loading
  const modalId = `modal_service_div-${UUID.genV4().hexNoDelim}`; // 弹窗id
  const Component = options.component; // 弹窗组件
  let isFormModal = false; // 是否是表单弹窗
  const formMoel = ref(getModel());
  const formRef = ref(null);

  const modalOption = reactive({ ...options.modalOption });
  const title = ref(modalOption.title || '');
  const formList = ref(options.formList);
  const confirmBtnText = ref(modalOption.confirmBtnText || '确定');
  const cancelBtnText = ref(modalOption.cancelBtnText || '取消');
  const showResetBtn = ref(modalOption.showResetBtn || false);
  const showConfirmBtn = ref(modalOption.showConfirmBtn || true);
  // const showCancelBtn = ref(modalOption.showCancelBtn || true);
  // const width = ref(modalOption.width || '800px');
  // const height = ref(modalOption.height || 'auto');
  // const wrapClassName = ref(modalOption.wrapClassName || '');
  // const wrapStyle = ref(modalOption.wrapStyle || {});
  // const mask = ref(modalOption.mask);
  // const destroyOnClose = ref(modalOption.destroyOnClose === undefined ? true : modalOption.destroyOnClose);
  // const centered = ref(modalOption.centered);
  // const showFooter = ref(modalOption.showFooter || false);
  const width = ref(modalOption.width || '800px');
  const height = ref(modalOption.height || 'auto');

  if (options.formList?.length) {
    isFormModal = true;
  }

  // 获取form的Model
  function getModel() {
    const model: Model = {};
    options.formList?.forEach((item: any) => {
      if (item.key) {
        model[item.key] = options?.formData?.[item.key] || item.value || null;
      }
    });
    return model;
  }

  // 表单校验
  async function validateForm() {
    const formData: any = { ...(formRef.value || {}) };
    await formData.validateForm();
  }

  // 初始化弹窗
  function init() {
    if (!globalModalDiv) {
      globalModalDiv = document.createElement('div');
      globalModalDiv.id = modalId;
      document.body.appendChild(globalModalDiv);
    }

    // showCancelBtn={showCancelBtn}
    // showFooter={showFooter}
    // width={width}
    // height={height}
    // wrapClassName={wrapClassName}
    // wrapStyle={wrapStyle}
    // mask={mask}
    // destroyOnClose={destroyOnClose}
    // centered={centered}
    // title={title}
    // confirmBtnText={confirmBtnText}
    // cancelBtnText={cancelBtnText}
    // showResetBtn={showResetBtn}
    // showConfirmBtn={showConfirmBtn}
    const ModalApp = (
      <ModalComponent
        {...modalOption}
        onClose={() => {
          handleClose();
          formMoel.value = getModel();
          options.onClose && options.onClose();
        }}
        onOk={async () => {
          if (isFormModal) {
            await validateForm();
          }
          options.onOk && options.onOk(formMoel.value);
        }}
        onReset={() => {
          options.onReset && options.onReset();
        }}
        title={title as any}
        visible={show}
        loading={loading}
      >
        <ConfigProvider locale={zhCN}>
          {isFormModal ? (
            <ModalForm ref={formRef} formList={formList.value} v-model:model={formMoel.value}></ModalForm>
          ) : (
            <Component></Component>
          )}
        </ConfigProvider>
      </ModalComponent>
    );

    if (!globalApp) {
      globalApp = createApp(ModalApp);
      globalApp.mount(`#${modalId}`);
      document.getElementById(modalId)?.remove();
    }
  }
  nextTick(() => init());
  // 展示和初始化弹出框
  function handleShow(formData?: Model) {
    nextTick(() => {
      if (formData) {
        formMoel.value = deepClone(formData);
      }
    });

    show.value = true;
  }

  function handleReset() {
    formMoel.value = getModel();
  }

  function handleClose() {
    show.value = false;
    handleLoading(false);
  }

  // 显示和隐藏loading
  function handleLoading(value: boolean) {
    loading.value = value;
  }

  function updateModalOptions(option: Partial<ModalOption>) {
    Object.assign(modalOption, option);
    title.value = option.title || modalOption.title || '';
    confirmBtnText.value = option.confirmBtnText || modalOption.confirmBtnText || '确定';
    cancelBtnText.value = option.cancelBtnText || modalOption.cancelBtnText || '取消';
    showResetBtn.value = option.showResetBtn || modalOption.showResetBtn || false;
    showConfirmBtn.value = option.showConfirmBtn || modalOption.showConfirmBtn || true;
  }

  return { handleShow, handleClose, handleLoading, updateModalOptions, handleReset };
}
